package com.atguigu.tingshu.user.api;

import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.common.login.annotation.TingshuLogin;
import com.atguigu.tingshu.common.result.Result;
import com.atguigu.tingshu.common.result.ResultCodeEnum;
import com.atguigu.tingshu.common.util.AuthContextHolder;
import com.atguigu.tingshu.model.user.UserInfo;
import com.atguigu.tingshu.user.service.UserInfoService;
import com.atguigu.tingshu.vo.user.UserInfoVo;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.bson.types.Code;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@Tag(name = "微信授权登录接口")
@RestController
@RequestMapping("/api/user/wxLogin")
@Slf4j
public class WxLoginApiController {

    @Autowired
    private UserInfoService userInfoService;

    @GetMapping("/wxLogin/{code}")
    @Operation(summary = "微信小程序登录")
    public Result wxLogin(@PathVariable(value = "code") String code) {
        Map<String, Object> map = userInfoService.WxLogin(code);
        return Result.ok(map);
    }

    @GetMapping("/getUserInfo")
    @Operation(summary = "获取用户信息")
    @TingshuLogin
    public Result getUserInfo() {
        // 从ThreadLocal中获取userId
        Long userId = AuthContextHolder.getUserId();

        UserInfo userInfo = userInfoService.getById(userId);
        if (userInfo == null) {
            throw new GuiguException(201, "该用户不存在");
        }

        UserInfoVo userInfoVo = new UserInfoVo();
        BeanUtils.copyProperties(userInfo, userInfoVo);
        return Result.ok(userInfoVo);
    }

    @PostMapping("/updateUser")
    @Operation(summary = "更新用户信息")
    @TingshuLogin
    public Result updateUser(@RequestBody UserInfoVo userInfoVo){
        userInfoService.updateUser(userInfoVo);
        return Result.ok();
    }

    @GetMapping("/refreshToken/getNewAccessToken")
    @Operation(summary = "获取新令牌")
    public Result getNewAccessToken() {

        Map<String, Object> map = userInfoService.getNewAccessToken();
        String flag = (String) map.get("1");
        if (map != null && flag.equals("v")) {
            return Result.build(null, ResultCodeEnum.LOGIN_AUTH);
        }
        return Result.ok(map);
    }

}
